<template>
  <div class="p-16px">
    <el-card>
      <el-button type="primary" @click="handleCreate">新建</el-button>
    </el-card>
    <el-card class="mt-16px">
      <el-table :data="tableData" border row-key="id" v-loading="loading">
        <el-table-column
          prop=""
          label="编号"
          type="index"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="200"
        ></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleUpdate(row)"
              v-if="row.roleName !== 'admin'"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
              v-if="row.roleName !== 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :title="form.id ? '编辑角色' : '新建角色'"
      v-model="isShowDialog"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限" prop="menuIds">
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="roleList"
            :default-checked-keys="form.menuIds"
            :props="{
              label: 'title',
              children: 'menuChild',
            }"
            show-checkbox
            node-key="id"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="isShowDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import { flattenArray } from "@/utils";
import dayjs from "dayjs";
const { getRoleList, getMenuTree, createRole, deleteRole, getRoleDetail } =
  useUserStore();

const roleList = ref([]);
const tableData = ref([]);
const loading = ref(false);
const isShowDialog = ref(false);
const currentPage = ref(1);
const pageSize = ref(1000);
const total = ref(0);
const defaultFormData = {
  id: undefined,
  roleName: "",
  menuIds: [],
};
const treeRef = ref(null);
const form = ref({
  ...defaultFormData,
});
const fetchMenuTree = () => {
  getMenuTree().then((res) => {
    roleList.value = res;
  });
};
const fetchList = () => {
  loading.value = true;
  getRoleList({
    current: currentPage.value,
    size: pageSize.value,
  })
    .then((res) => {
      console.log(res);
      tableData.value = res.records.map((item) => ({
        ...item,
        createTime: dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
      }));
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSubmit = () => {
  const menuIds = treeRef.value.getCheckedKeys();
  console.log(menuIds);
  form.value.menuIds = menuIds;
  createRole(form.value).then((res) => {
    console.log(res);
    isShowDialog.value = false;
    fetchList();
  });
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchList();
};
const handleCreate = () => {
  form.value = { ...defaultFormData };
  isShowDialog.value = true;
};
const handleUpdate = (row) => {
  getRoleDetail({ id: row.id }).then((res) => {
    const menuIds = flattenArray(res.roleMenuTree, "menuChild")
      .filter((item) => item.isHave)
      .map((item) => item.id);
    console.log(menuIds);

    form.value = { ...row, menuIds };
    isShowDialog.value = true;
    treeRef.value.setCheckedKeys(menuIds, false);
  });
};
const handleDelete = (row) => {
  ElMessageBox.confirm("确定删除该角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "删除中...";
        deleteRole({
          idList: row.id,
        }).then((res) => {
          console.log(res);
          done();
          fetchList();
        });
      } else {
        done();
      }
    },
  });
};

onMounted(() => {
  fetchList();
  fetchMenuTree();
});
</script>

<style lang="scss" scoped></style>
